package com.anolesoft.twelvePlan.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.exception.ExcelAnalysisStopException;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.StringUtils;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.twelvePlan.dto.MesEqualCatalogExport;
import com.anolesoft.twelvePlan.dto.MesGyInfoExport;
import com.anolesoft.twelvePlan.entity.MesEqualCatalogDO;
import com.anolesoft.twelvePlan.entity.MesGyInfoDO;
import com.anolesoft.twelvePlan.service.MesEqualCatalogService;
import com.anolesoft.twelvePlan.service.MesGyInfoService;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author zyq
 * @date 2022/5/15
 */
@Slf4j
public class MesEqualCatalogListener implements ReadListener<MesEqualCatalogExport> {
    private static final int BATCH_COUNT = 1000;

    private List<MesEqualCatalogExport> list = new ArrayList<>();

    private List<MesEqualCatalogDO> communityList = new ArrayList<>(BATCH_COUNT);

    private MesEqualCatalogService mesEqualCatalogService;

    public MesEqualCatalogListener(MesEqualCatalogService mesEqualCatalogService){
        this.mesEqualCatalogService = mesEqualCatalogService;
    }

    private String[] compare;

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {
        log.error("报错原因："+e.getMessage());
        int row=0,column=0;
        String message = "";
        if (e instanceof ExcelDataConvertException){
            ExcelDataConvertException convertException=(ExcelDataConvertException) e;

            row=convertException.getRowIndex();
            column=convertException.getColumnIndex();
            log.error("解析出错：{}行 {}列",row,column);
            message = "解析出错："+row+"行 "+column+"列，停止运行";
        } else {
            message = "模板错误，请检查导入模板";
        }
        //throw new ExcelAnalysisStopException(message);
        throw new ExcelAnalysisException(message);
    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {
        Map<Integer, String> head = ConverterUtils.convertToStringMap(map, analysisContext);
        log.info("解析到一条头数据:{}", head);
        // 获取实体类字段列表
        Field[] fields = MesEqualCatalogExport.class.getDeclaredFields();
        int count = 0;
        for (Field field : fields) {
            // 获取当前字段上的ExcelProperty注解信息
            ExcelProperty fieldAnnotation = field.getAnnotation(ExcelProperty.class);
            // 判断当前字段上是否存在ExcelProperty注解
            if (fieldAnnotation != null) {
                ++count;
                // 存在ExcelProperty注解则根据注解的index索引到表头中获取对应的表头名
                String headName = head.get(fieldAnnotation.index());
                //System.out.println(">>>>>>>>>>>>>>>>>表头名"+headName);
                // 判断表头是否为空或是否和当前字段设置的表头名不相同
                if (StringUtils.isEmpty(headName) || !headName.equals(fieldAnnotation.value()[0])) {
                    // 如果为空或不相同，则抛出异常不再往下执行
                    throw new ExcelAnalysisStopException("模板错误，请检查导入模板");
                }
            }
        }
        // 判断用户导入表格的标题头是否完全符合模板
        if (count != head.size()) {
            throw new ExcelAnalysisStopException("模板错误，请检查导入模板");
        }
    }

    @Override
    public void invoke(MesEqualCatalogExport mesEqualCatalogExport, AnalysisContext analysisContext) {
        //analysisContext.readWorkbookHolder().setIgnoreEmptyRow(false);
        //MesGyInfoDO mesGyInfoDO = new MesGyInfoDO();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        MesEqualCatalogDO mesEqualCatalogDO = BeanUtil.copyProperties(mesEqualCatalogExport, MesEqualCatalogDO.class);
        mesEqualCatalogDO.setCreateuid(loginUser.getEmpUid());
        mesEqualCatalogDO.setFactoryId(loginUser.getFacCode());
        //log.debug("数据：{}", mesEqualCatalogDO);


        communityList.add(mesEqualCatalogDO);
        if (communityList.size() >= BATCH_COUNT) {
            batchInsert();
            // 存储完成清理 list
            communityList.clear();
        }
    }

    @Override
    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        batchInsert();
    }

    /**
     * 重写此方法时默认返回false 需改成true
     * @param analysisContext
     * @return
     */
    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return true;
    }

    void batchInsert(){
        log.debug("数据：{}", communityList);
        mesEqualCatalogService.uploadEqualCatalog(communityList);
    }
}
